import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app_badger/flutter_app_badger.dart';
import 'package:jpush_flutter/jpush_flutter.dart';
import 'package:yuan_hang_app/res/w_colors.dart';
import 'package:yuan_hang_app/res/w_constant.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/utils/string_utils.dart';
import 'package:yuan_hang_app/widget/common_dialog.dart';
import 'package:yuan_hang_app/widget/custom_tab.dart';
import 'package:yuan_hang_app/widget/status_btn.dart';
import 'package:yuan_hang_app/widget/w_text.dart';
import '../../base/base_state.dart';
import '../../base/full_base_page.dart';
import '../../http/api.dart';
import '../../http/http_utils.dart';
import '../../res/w_dimens.dart';
import '../../utils/router_helper.dart';
import '../../widget/w_list_view.dart';
import '../../widget/w_toast.dart';
import '../home/view/book/book_manage_page.dart';
import '../home/view/drive/drive_feedback_page.dart';
import '../home/view/leads/defeat_audit_page.dart';
import '../home/view/leads/leads_assign_page.dart';
import '../home/view/leads/leads_follow_up_page.dart';
import '../home/view/leads/leads_pool_page.dart';

class AlertMsgPage extends StatefulWidget {
  const AlertMsgPage({super.key});

  @override
  BaseState<AlertMsgPage> createState() => _AlertMsgPageState();
}

class _AlertMsgPageState extends BaseState<AlertMsgPage> {
  // 假设消息数据，需要根据实际情况进行填充
  List<Map> allMessagesListRow = [];

  List currentAlertList = [];
  var mCurrentStatus;
  int mPage = 0;
  String keyword = "";
  List<Map> tabs = [
    {"title": "未读", "count": 0},
    {"title": "已读", "count": 0},
  ];

  int selectedIndex = 0;

  int unReadCount = 0;

  @override
  FullBasePage buildState(BuildContext context) {
    return FullBasePage(
        title: "消息提醒",
        rightWidget: Row(
            mainAxisAlignment: MainAxisAlignment.end,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Offstage(
                offstage: selectedIndex == 1,
                child: GestureDetector(
                  onTap: () {
                    CommonDialog.showConformDialog(
                      context: context,
                      title: "提示",
                      content: "你确认全部已读",
                      onConfirm: (text) {
                        if (currentAlertList.isEmpty) {
                          Toast.toast("暂无未读消息可操作");
                          return;
                        }
                        //这里判断下如果是已读接口不再调
                        Map<String, dynamic> dataMap = {"todoTaskType": 1};
                        showLoading();
                        HttpUtils()
                            .post(Api.updateAlertMessage, data: dataMap)
                            .then((data) {
                          hideLoading();
                          if (data.resultCode == 200) {
                            for (int i = 0; i < currentAlertList.length; i++) {
                              currentAlertList[i]["taskStatus"] = 1;
                            }
                            if (Platform.isAndroid) {
                              FlutterAppBadger.updateBadgeCount(0);
                            } else if (Platform.isIOS) {
                              JPush().setBadge(0);
                            }
                            setState(() {});
                            fetchDataList();
                          } else {
                            Toast.toast(data.errMsg ?? "");
                          }
                        }).catchError((e) {
                          hideLoading();
                        });
                        setState(() {});
                      },
                    );
                  },
                  child: Row(
                    children: [
                      Image.asset(
                        "images/ic_msg_read.png",
                        width: 14.px,
                      ),
                      SizedBox(
                        width: 3.px,
                      ),
                      WText(
                        "已读",
                        style: TextStyle(
                          color: WColors.mainTextColor,
                          fontSize: WDimens.tsLabel,
                        ),
                      ),
                    ],
                  ),
                ),
              )
            ]),
        child: Column(
          children: <Widget>[
            CustomTab(
              tabList: tabs,
              tabClick: (index) {
                selectedIndex = index;
                mPage = 1;
                showLoading();
                fetchDataList();
              },
            ),
            Expanded(
              child: WListView(
                padding: EdgeInsets.only(top: 10.px),
                itemBuilder: _noticeMsgItem,
                getDataList: (currentState, page) {
                  mCurrentStatus = currentState;
                  mPage = page;
                  fetchDataList();
                },
              ),
            )
          ],
        ));
  }

  Widget _noticeMsgItem(context, index, currentAlertList) {
    Map message = currentAlertList[index];
    return GestureDetector(
        onTap: () {
          if (Platform.isAndroid) {
            FlutterAppBadger.updateBadgeCount(unReadCount);
          } else if (Platform.isIOS) {
            JPush().setBadge(unReadCount);
          }
          ///更新已读接口--单个的 做状态控制
          if (message["taskStatus"] == 0) {
            Map<String, dynamic> dataMap = {
              "todoTaskId": message["taskId"],
              "todoTaskType": 0
            };
            HttpUtils()
                .post(Api.updateAlertMessage, data: dataMap)
                .then((data) {
              hideLoading();
              if (data.resultCode == 200) {
                currentAlertList[index]["taskStatus"] = 1;
                setState(() {});
              } else if (data.resultCode == 500) {
                Toast.toast(data.errMsg ?? "");
              }
            });
          }

          switch (message["taskTitle"]) {
            case "线索分配":
              RouteHelper.pushWidget(
                      context, LeadsFollowUpPage(phone: message["phone"]))
                  .then((value) {
                if (value == null || value == true) {
                  fetchDataList();
                  setState(() {});
                }
              });
              break;
            case "线索下发":
              RouteHelper.pushWidget(
                      context, LeadsAssignPage(phone: message["phone"]))
                  .then((value) {
                if (value == null || value == true) {
                  fetchDataList();
                  setState(() {});
                }
              });
              break;
            case "试驾回访":
              RouteHelper.pushWidget(
                      context, DriveFeedBackPage(phone: message["phone"]))
                  .then((value) {
                if (value == null || value == true) {
                  fetchDataList();
                  setState(() {});
                }
              });
              break;
            case "客户预约":
              RouteHelper.pushWidget(
                      context, BookManagePage(phone: message["phone"]))
                  .then((value) {
                if (value == null || value == true) {
                  fetchDataList();
                  setState(() {});
                }
              });
              break;
            case "战败审核":
              RouteHelper.pushWidget(
                      context, DefeatAuditPage(phone: message["phone"]))
                  .then((value) {
                if (value == null || value == true) {
                  fetchDataList();
                  setState(() {});
                }
              });
            case "抢线索":
              RouteHelper.pushWidget(
                  context, LeadsPoolPage(phone: message["phone"]))
                  .then((value) {
                if (value == null || value == true) {
                  fetchDataList();
                  setState(() {});
                }
              });
              break;
            case "共同跟进":
              RouteHelper.pushWidget(
                  context, LeadsFollowUpPage(phone: message["phone"]))
                  .then((value) {
                if (value == null || value == true) {
                  fetchDataList();
                  setState(() {});
                }
              });
              break;
          }
        },
        child: Container(
            alignment: Alignment.center,
            margin: EdgeInsets.only(left: 15.px, right: 15.px, bottom: 10.px),
            padding: EdgeInsets.all(10.px),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10.px),
                color: Colors.white,
                boxShadow: const [
                  BoxShadow(
                      //线框阴影线条
                      color: WColors.border,
                      offset: Offset(0, 1),
                      blurRadius: 2)
                ]),
            child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Row(
                        children: [
                          Offstage(
                            offstage: message["taskStatus"] == 1,
                            child: StatusBtn(
                              width: 10.px,
                              height: 10.px,
                              radius: 8.px,
                              isItemBtn: true,
                              isBg: true,
                              color: WColors.redMain,
                              margin: EdgeInsets.only(right: 5.px),
                            ),
                          ),
                          SizedBox(
                            width: message["taskStatus"] == 1 ? 15 : 0,
                          ),
                          WText(
                              StringUtils.safeGetValue(message['taskTitle'],
                                  placeHolder: "未知"),
                              style: TextStyle(
                                  fontSize: WDimens.tsLarge,
                                  color: WColors.mainTextColor,
                                  fontWeight: FontWeight.bold))
                        ],
                      ),
                      Text(
                        StringUtils.safeGetValue(message["createDate"],
                            placeHolder: "-"),
                        style: TextStyle(
                            color: const Color(0xFF999999), fontSize: 12.px),
                      ),
                    ],
                  ),
                  SizedBox(height: 8.px),
                  Padding(
                    padding: EdgeInsets.only(left: 15.px, bottom: 10.px),
                    child: WText(
                        StringUtils.safeGetValue(message['taskMsg'],
                            placeHolder: "未知"),
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                          fontSize: WDimens.tsMedium,
                          color: WColors.hintTextColor,
                        )),
                  ),
                ])));
  }

  void fetchDataList() {
    HttpUtils()
        .get(
            "${Api.getAlertMessageList}?currentPage=$mPage&pageSize=20&status=$selectedIndex")
        .then((value) {
      if (value.resultCode == 200) {
        hideLoading();
        List list = value.data["list"]["records"];
        mCurrentStatus.onRefreshData(list, mPage);
        if (mPage == 1) {
          tabs[0]["count"] = value.data["unreadNum"] ?? 0;
          tabs[1]["count"] = value.data["readNum"] ?? 0;
          setState(() {});
          currentAlertList.clear();
        }
        currentAlertList.addAll(list);
      } else {
        mCurrentStatus?.onFail(value.errMsg);
      }
    }).catchError((e) {
      hideLoading();
    });
  }

  @override
  void initState() {
    super.initState();
    getUnreadCount();
  }

  Future<Null> getUnreadCount() async {
    HttpUtils()
        .get(
            "${Api.getNoticeMessageCount}?userId=${WConstant().userInfo.userId}")
        .then((value) {
      if (value.resultCode == 200 && value.data["resultCode"] == 200) {
        var msgCount = value.data["data"];
        //  int count1 = msgCount?['notNum'] ?? 0;
        unReadCount = msgCount?['taskNum'] ?? 0;
        if (unReadCount <= 1) {
          unReadCount = 0;
        } else {
          unReadCount--;
        }
        // int count = count1 + count2 - 1;
        setState(() {});
      } else {
        Toast.toast(value.errMsg ?? "");
      }
    }).catchError((e) {});
  }
}
